//给定一个大小为 n 的数组，找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 
//
// 你可以假设数组是非空的，并且给定的数组总是存在多数元素。 
//
// 
//
// 示例 1: 
//
// 输入: [3,2,3]
//输出: 3 
//
// 示例 2: 
//
// 输入: [2,2,1,1,1,2,2]
//输出: 2
// 
// Related Topics 位运算 数组 分治算法

package leetcode.editor.cn;

public class MajorityElement {
    public static void main(String[] args) {
        Solution solution = new MajorityElement().new Solution();
        int i = solution.majorityElement(new int[]{6,5,5});
        System.out.println(i);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int majorityElement(int[] nums) {
            return majorityElementInternally(nums,0,nums.length - 1);
        }

        public int majorityElementInternally(int[] nums,int left,int right) {
            if (left == right) {
                return nums[left];
            }

            int mid = (left + right)/2;
            int leftMajority = majorityElementInternally(nums, left, mid);
            int rightMajority = majorityElementInternally(nums, mid + 1, right);

            if (leftMajority == rightMajority) {
                return leftMajority;
            }

            // 计算左边众数出现了多少次
            int calculateOfLeft = calculate(nums, left, mid, leftMajority);
            int calculateOfRight = calculate(nums, mid+1, right, rightMajority);
            if (calculateOfLeft > calculateOfRight) {
                return leftMajority;
            } else {
                return rightMajority;
            }
        }

        int calculate(int[] nums, int left, int right, int target) {
            int sum = 0;
            for (int i = left; i <= right; i++) {
                if (nums[i] == target) {
                    sum++;
                }
            }

            return sum;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}